package com.wmyg.scanninggun.controller;

import com.wmyg.scanninggun.bean.Bill;
import com.wmyg.antifake.enums.DataPrepareState;
import com.wmyg.scanninggun.bean.BillNew;
import com.wmyg.scanninggun.bean.Factory;
import com.wmyg.scanninggun.message.BillRequest;
import com.wmyg.scanninggun.message.BillResponse;
import com.wmyg.scanninggun.message.DataPreparePo;
import com.wmyg.scanninggun.service.FactoryDeviceService;
import com.wmyg.scanninggun.service.PackageNewService;
import com.wmyg.scanninggun.service.PackageService;
import com.wmyg.scanninggun.utils.BillChecker;
import com.wmyg.scanninggun.utils.BillConverter;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/package")
public class PackageController {

    private static String batchBuffer;

    @Autowired
    PackageService packageService;

    @Autowired
    PackageNewService packageNewService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    FactoryDeviceService factoryDeviceService;
//    @Autowired
//    AmqpTemplate amqpTemplate;
    @RequestMapping(value = "/timeAlign.do")
    public void timeAlign(HttpResponse response) {
//        this.amqpTemplate.convertAndSend("blog1","{'s':'你好你好'}");
    }
    
    @RequestMapping(value = "/dataPrepare.do")
    public DataPreparePo dataPrepare(String qrBatch, String deviceId) {
        log.info("Device {} request to data prepare", deviceId);
        Factory factory = factoryDeviceService.getFactoryByDeviceId(deviceId);
        if (null == factory) {
            return new DataPreparePo(DataPrepareState.UNENROLL);
        }
        boolean tag = true;
        log.info("qr={}", qrBatch.length());
        //构建当天任务缓存项
        String messionTemp = "Mession" + factory.getFactoryId();
        if ("0".equals(qrBatch.trim())) {

            tag = false;
            log.info("Normal worker check data prepare");
            if (redisTemplate.hasKey(messionTemp)) {
                qrBatch = (String)redisTemplate.opsForValue().get(messionTemp) + "BCSJYDDX";
                log.info("Get the mission is {}", qrBatch);
            } else {
                log.info("Data prepare is not started");
                return new DataPreparePo(DataPrepareState.UNSTART);
            }
        } else {
            log.info("Manager check data prepare for batch {}", qrBatch);
            redisTemplate.opsForValue().set(messionTemp, qrBatch.substring(0,32));
        }
        return new DataPreparePo(packageService.dataPrepare(qrBatch.substring(0, 39), tag));
    }

    @RequestMapping(value = "/pack.do")
    public BillResponse pack(@RequestBody BillRequest billRequest) {
        log.info("Start to upload bill for case:{} with deviceId:{}", billRequest.getCaseId(), billRequest.getDeviceId());
        long start = System.currentTimeMillis();
        //根据请求体构建工单对象
        Bill bill = new Bill(billRequest);
        BillResponse billResponse = new BillResponse();
        Factory factory = factoryDeviceService.getFactoryByDeviceId(bill.getDeviceId());
        if (null == factory) {
            billResponse.setCode(-1);
            billResponse.setInfo("设备未注册");
            return billResponse;
        }
        bill.setFactoryId(factory.getFactoryId());
        bill.setFactoryName(factory.getFactoryName());
        if (!BillChecker.checkSimply(bill)) {
            billResponse.setCode(-1);
            billResponse.setInfo("工单数据有误");
            return billResponse;
        }
        //List<Bill> bills = packageService.selectInvailBills(bill.getDeviceId());
        //billResponse.setInvalidBills(bills);
        billResponse.setInvalidCount(packageService.selectInvalidCount(bill.getDeviceId(), billRequest.getStartTime()));
        billResponse.setValidCount(packageService.selectValidCount(bill.getDeviceId(), billRequest.getStartTime()));
        boolean result = packageService.pack(bill);
        //根据工单初步判断是否有效
        if (result) {
            log.info("The bill {} is valid and being checked...", bill);
            billResponse.setCode(0);
            billResponse.setInfo("工单上传成功，校验中。。。");
        } else {
            log.info("The bill {} is invaild", bill);
            billResponse.setCode(1);
            billResponse.setInfo("此工单无效");
        }
        long end = System.currentTimeMillis();
        log.info("The whole pack spend {}ms", end - start);
        //查询相应有效工单和无效工单
        return billResponse;
//        return null;
    }

    @RequestMapping(value = "/count.do")
    public Map<String, Integer> count(String deviceId, String startTime) {
        HashMap<String, Integer> countMap = new HashMap<>();
        countMap.put("valid", packageService.selectValidCount(deviceId, startTime));
        countMap.put("invalid", packageService.selectInvalidCount(deviceId, startTime));
        log.info("The device {} get count {} since {}", deviceId, countMap, startTime);
        return countMap;
    }

    @RequestMapping(value = "/packnew.do")
    public BillResponse packageNew(@RequestBody BillRequest billRequest) {
        log.info("NEW-----Start to upload bill for case:{} with deviceId:{}", billRequest.getCaseId(), billRequest.getDeviceId());
        long start = System.currentTimeMillis();
        BillResponse billResponse = new BillResponse();
        if (!BillChecker.check(billRequest)) {
            billResponse.setCode(-1);
            billResponse.setInfo("工单数据有误");
            return billResponse;
        }
        if (!BillChecker.checkBatch(billRequest)) {
            billResponse.setCode(-2);
            billResponse.setInfo("工单数据不在同一批次");
            return billResponse;
        }
        BillNew billNew = BillConverter.billRequest2BillNew(billRequest);
        Factory factory = factoryDeviceService.getFactoryByDeviceId(billNew.getDeviceId());
        if (null == factory) {
            billResponse.setCode(-1);
            billResponse.setInfo("设备未注册");
            return billResponse;
        }
        billNew.setFactoryId(factory.getFactoryId());
        billNew.setFactoryName(factory.getFactoryName());
        billResponse.setInvalidCount(packageNewService.selectInvalidCount(billNew.getDeviceId(), billRequest.getStartTime()));
        billResponse.setValidCount(packageNewService.selectValidCount(billNew.getDeviceId(), billRequest.getStartTime()));
        boolean result = packageNewService.pack(billNew);
        //根据工单初步判断是否有效
        if (result) {
            log.info("NEW-----The bill {} is valid and being checked...", billNew);
            billResponse.setCode(0);
            billResponse.setInfo("工单上传成功，校验中。。。");
        } else {
            log.info("NEW-----The bill {} is invaild", billNew);
            billResponse.setCode(1);
            billResponse.setInfo("此工单无效");
        }
        long end = System.currentTimeMillis();
        log.info("NEW-----The whole new pack spend {}ms", end - start);
        //查询相应有效工单和无效工单
        return billResponse;
    }

    @RequestMapping(value = "/newcount.do")
    public Map<String, Integer> newCount(String deviceId, String startTime) {
        HashMap<String, Integer> countMap = new HashMap<>();
        countMap.put("valid", packageNewService.selectValidCount(deviceId, startTime));
        countMap.put("invalid", packageNewService.selectInvalidCount(deviceId, startTime));
        log.info("NEW-----The device {} get count {} since {}", deviceId, countMap, startTime);
        return countMap;
    }

}
